package com.kgcx.oagateway.service;

import com.kgcx.common.bean.ReturnData;
import com.kgcx.common.client.organization.CustomerClient;
import com.kgcx.common.client.organization.DriverClient;
import com.kgcx.common.client.organization.WebUserClient;
import com.kgcx.common.client.organization.pojo.Customer;
import com.kgcx.common.client.organization.pojo.Driver;
import com.kgcx.common.client.organization.pojo.User;
import com.kgcx.common.redis.JsonRedisTemplate;
import com.kgcx.common.redis.RedisCons;
import com.kgcx.common.utils.CollectionUtils;
import com.kgcx.common.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Set;

/**
 * @author 吴刚林
 * @date 2017/11/30
 */
@Service
@Slf4j
public class TokenService {

    @Autowired
    private DriverClient driverClient;
    @Autowired
    private CustomerClient customerClient;
    @Autowired
    private JsonRedisTemplate jsonRedisTemplate;
    @Resource
    private WebUserClient webUserClient;

    @Scheduled(cron = "0 0 0 * * ?")   //每天0点触发
    public void cleanTokenRedis() {
        HashOperations hashOperations = jsonRedisTemplate.opsForHash();
        Set keys = hashOperations.keys(RedisCons.TOKEN);
        if (CollectionUtils.isNotEmpty(keys)) {
            keys.forEach(i -> hashOperations.delete(RedisCons.TOKEN, i));
        }
    }

    public boolean validateToken(String token, String subject, String id) {
        HashOperations hashOperations = jsonRedisTemplate.opsForHash();
        Object obj = hashOperations.get(RedisCons.TOKEN, token);
        if (null != obj) {
            return true;
        } else {
            if (TokenUtils.TOKEN_SUBJECT_DRIVER.equals(subject)) {

                Driver driver = driverClient.getDriver(Long.valueOf(id), null);
                if (driver != null) {
                    hashOperations.put(RedisCons.TOKEN, token, id);
                    return true;
                }
            } else if (TokenUtils.TOKEN_SUBJECT_CUSTOMER.equals(subject)) {
                Customer customer = customerClient.getCustomer(Long.valueOf(id), null, null);
                if (customer != null) {
                    hashOperations.put(RedisCons.TOKEN, token, id);
                    return true;
                }
            } else if (TokenUtils.TOKEN_SUBJECT_WEBUSER.equals(subject)) {
                User user = webUserClient.getUserByAccount(id);
                if (user != null) {
                    hashOperations.put(RedisCons.TOKEN, token, id);
                    return true;
                }
            }
        }
        return false;
    }
}
